package com.kob.matchingsystem.service.impl.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 匹配池
 *
 * @Author: CZY
 * @date: 2024/9/2 23:01
 */
@Component
public class MatchingPool extends Thread {

    // 所有等待匹配的玩家
    private static List<Player> players = new ArrayList<>();
    private final ReentrantLock lock = new ReentrantLock();
    private static RestTemplate restTemplate;
    private final static String startGameUrl = "http://127.0.0.1:3000/pk/start/game/";

    @Autowired
    public void setRestTemplate(RestTemplate restTemplate) {
        MatchingPool.restTemplate = restTemplate;
    }

    // 将玩家添加到匹配池中
    public void addPlayer(Integer userId, Integer rating, Integer botId) {
        lock.lock();
        try {
            boolean f = false;
            for (Player player : players) {
                if (player.getUserId().equals(userId)) {
                    f = true;
                    break;
                }
            }
            if (!f) {
                players.add(new Player(userId, rating, botId, 0));
            }
        } finally {
            lock.unlock();
        }
    }

    // 从匹配池中移除指定玩家
    public void removePlayer(Integer userId) {
        lock.lock();
        try {
            // 创建一个新的列表，将不用删除的玩家存入新的链表
            List<Player> newPlayers = new ArrayList<>();
            for (Player player : players) {
                if (!player.getUserId().equals(userId)) {
                    newPlayers.add(player);
                }
            }
            players = newPlayers;
        } finally {
            lock.unlock();
        }
    }

    // 将所有当前玩家的等待时间加1
    private void increaseWaitingTime() {
        for (Player player : players) {
            player.setWaitingTime(player.getWaitingTime() + 1);
        }
    }

    // 判断两名玩家是否匹配
    private boolean checkMatched(Player a, Player b) {
        int ratingDelta = Math.abs(a.getRating() - b.getRating());
        int waitingTime = Math.max(a.getWaitingTime(), b.getWaitingTime());
        return ratingDelta <= waitingTime * 10;
    }

    // 返回匹配结果
    private void sendResult(Player a, Player b) {
//        System.out.println("send result: " + a + " " + b);
        MultiValueMap<String, String> data = new LinkedMultiValueMap<>();
        data.add("a_id", a.getUserId().toString());
        data.add("a_bot_id", a.getBotId().toString());
        data.add("b_id", b.getUserId().toString());
        data.add("b_bot_id", b.getBotId().toString());
        data.add("difficulty", "none");
        restTemplate.postForObject(startGameUrl, data, String.class);
    }

    // 尝试匹配所有玩家
    private void matchPlayers() {
//        System.out.println("match players: " + players.toString());
        boolean[] used = new boolean[players.size()];
        for (int i = 0; i < players.size(); i++) {
            if (used[i]) continue;
            Player a = players.get(i);

            // 检查等待时间是否超过15秒
            if (a.getWaitingTime() > 15) {
                // 匹配机器人用户
                Player botPlayer = new Player(5, 1500, 5, 0);
                sendResult(a, botPlayer);
                used[i] = true;
            } else {
                for (int j = i + 1; j < players.size(); j++) {
                    if (used[j]) continue;
                    Player b = players.get(j);
                    if (checkMatched(a, b)) {
                        used[i] = used[j] = true;
                        sendResult(a, b);
                        break;
                    }
                }
            }
        }

        // 删除匹配成功的玩家
        List<Player> newPlayers = new ArrayList<>();
        for (int i = 0; i < players.size(); i++) {
            if (!used[i]) {
                newPlayers.add(players.get(i));
            }
        }
        players = newPlayers;
    }

    // 在后台不断尝试匹配玩家
    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(1000);
                lock.lock();
                try {
                    increaseWaitingTime();
                    matchPlayers();
                } finally {
                    lock.unlock();
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
                break;
            }
        }
    }
}
